package com.ysu.shop.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ysu.shop.exception.UserNoLoginException;
import com.ysu.shop.pojo.User;
import com.ysu.shop.service.IPermissionService;
import com.ysu.shop.pojo.Permission;

import com.ysu.shop.service.IUserService;
import com.ysu.shop.utils.JwtUtil;
import com.ysu.shop.utils.Result;
import com.ysu.shop.utils.InitUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.web.bind.annotation.*;


import lombok.extern.slf4j.Slf4j;

/**
* <p>
    * 权限 前端控制器
    * </p>
*
* @author 耿志龙
* @since 2020-10-01
*/
@RestController
@Slf4j
@RequestMapping("/permissions")
public class PermissionController {

    @Resource
    private IPermissionService iPermissionService;

    @Resource
    private IUserService userService;


    /**
     * 通过主键id在表中查找信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable int id) {
        Permission iPermission = iPermissionService.getById(id);
        if (iPermission == null) {
            return Result.getFailResult("", "无记录");
        }
        return Result.getSuccessResult(iPermission);
    }

    /**
     * 获取树形的权限树
     */
    @GetMapping
    public Result getListByTree() {
        return Result.getSuccessResult(iPermissionService.listByTree());
    }

    /**
     * 获取所有的一级权限
     * @return
     */
    @GetMapping("/parent")
    public Result getParent(){
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<Permission> list =  iPermissionService.list(wrapper);
        List<Integer> ids = new ArrayList<>();
        for(Permission i : list){
            ids.add(i.getId());
        }
        return Result.getSuccessResult(ids);
    }

    /**
     * 根据用户的角色类型获取菜单
     */
    @GetMapping("/userPermissionList")
    public Result userPermissionList(HttpServletRequest request){
        int userId = JwtUtil.getUserId(request);
        User user = userService.getById(userId);
        if (user==null) {
            throw new UserNoLoginException();
        }
        return Result.getSuccessResult(iPermissionService.userPermissionList(user.getRoleId()));
    }

    /**
    * name : 需要检查那个字段的value是否在数据库存在
    * 比如/check/RegistworkName?value=阿司匹林  ：检查数据库是否存在RegistworkName='阿司匹林'
    */
    @GetMapping("/check/{name}")
    public Result checkName(@PathVariable String name,@RequestParam String value){
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq(name, value);
        if (iPermissionService.getOne(wrapper) != null){
        return Result.getFailResult();
        }
        return Result.getSuccessResult();
    }

    /**
    * 向表中添加一条记录
    */
    @PostMapping()
    public Result save(@RequestBody Permission iPermission) {
        if (iPermissionService.save(iPermission)){
            return Result.getSuccessResult("","添加成功");
        }
        return Result.getFailResult("","添加失败");
    }

    /**
    * 根据表中的主键修改 根据表中字段相应的修改，如果存在则修改
    */
    @PutMapping("/{id}")
    public Result update(@RequestBody Permission iPermission, @PathVariable int id) {
        iPermission.setId(id);
        if (iPermissionService.updateById(iPermission)){
        return Result.getSuccessResult("","修改成功");
        }
        return Result.getFailResult("","修改失败");
    }

    /**
    * active 字段 相当于激活一样 设置字段的有效性 active=1 有效
    */
    @PutMapping("/back/{id}")
    public Result back(@PathVariable int id) {
        Permission iPermission = new Permission();
        iPermission.setId(id);
        iPermission.setActive(1);
        if (iPermissionService.updateById(iPermission)){
            return Result.getSuccessResult("","激活成功");
        }
        return Result.getFailResult("","激活失败");
    }

    /**
    * active 字段 相当于激活一样 设置字段的有效性 active=0 无效 逻辑删除
    */
    @PutMapping("/del/{id}")
    public Result loginDel(@PathVariable int id) {
        Permission iPermission = new Permission();
        iPermission.setId(id);
        iPermission.setActive(0);
        if (iPermissionService.updateById(iPermission)){
            return Result.getSuccessResult("","设置失效成功");
        }
        return Result.getFailResult("","设置失效失败");
    }

    /**
    * 批量设置 active=0
    */
    @PutMapping("/batchDel")
    public Result LoginBatchDel(@RequestParam String ids) {
        Permission iPermission = new Permission();
        iPermission.setActive(0);
        String[] idList = ids.split(",");
        for (String id : idList) {
            iPermission.setId(Integer.parseInt(id));
            iPermissionService.updateById(iPermission);
        }
        return Result.getSuccessResult("","批量失效成功");
    }

    /**
    * 在数据表中真正的删除一条记录
    */
    @DeleteMapping("/{id}")
    public Result delById(@PathVariable int id) {
        if (id<10) {
            return Result.getFailResult("","不能删除系统预留项");
        }
        if (iPermissionService.removeById(id)){
            return Result.getSuccessResult("","删除成功");
        }
        return Result.getFailResult("","删除失败");
    }

}
